<template>
  <div>
    <el-card>
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button type="primary" size="default" @click="addTrade" icon="Plus">
        添加品牌
      </el-button>
      <!-- 表格组件：用于展示品牌 -->
      <el-table style="margin: 10px 0px" :border="true" :data="tradeMarkArr">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column
          label="品牌名称"
          align="center"
          prop="tmName"
        ></el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" alt="图片显示错误" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作" align="center" width="300px">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              plain
              icon="Edit"
              @click="updateTrade(row)"
            >
              修改
            </el-button>
            <el-popconfirm
              :title="`您确定要删除${row.tmName}吗？`"
              width="250px"
              icon="Delete"
              @confirm="deleteTradeMark(row.id)"
            >
              <template #reference>
                <el-button type="danger" plain icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        v-model:current-page="currentPage"
        @size-change="sizeChange"
        @current-change="changePageNO"
        :page-sizes="[3, 5, 7, 9]"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper, -> ,sizes, total"
        :total="total"
        background
      >
        :pager-count="7">
      </el-pagination>
    </el-card>
    <!-- 对话框组件:在添加品牌鱼修改已有品牌的业务时使用的结构 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="tradeMarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        ref="formRef"
        style="width: 80%"
        :model="tradeMarkParams"
        :rules="rules"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请你输入品牌名称"
            size="normal"
            v-model="tradeMarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :before-upload="beforeUpload"
            :on-success="successUpload"
          >
            <img
              v-if="tradeMarkParams.logoUrl"
              :src="tradeMarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 -->
      <template #footer>
        <el-button type="primary" size="default" @click="cancel">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="confirm">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive, nextTick } from 'vue'
import {
  reqHasTradeMark,
  reqAddOrUpdateTradeMark,
  reqDeleteTradeMark,
} from '@/api/product/tradeMark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/tradeMark/type'
import { ElMessage, type UploadProps } from 'element-plus'
// 当前页码
let currentPage = ref<number>(1)
// 每一页展示条数
let pageSize = ref<number>(5)
// 存储已有品牌的数据总数
let total = ref<number>(0)
// 获取已有品牌数据
let tradeMarkArr = ref<Records>([])
// 控制对话框的显示与隐藏
let dialogFormVisible = ref(false)
// 定义手机新增品牌数据
let tradeMarkParams = reactive<TradeMark>({
  logoUrl: '',
  tmName: '',
})
// 获取el-form组件实例
let formRef = ref()

// 封装获取已有品牌的接口为一个函数
const getHasTradeMark = async () => {
  const result: TradeMarkResponseData = await reqHasTradeMark(
    currentPage.value,
    pageSize.value,
  )
  if (result.code == 200) {
    // 存储已有品牌的总个数
    total.value = result.data.total
    tradeMarkArr.value = result.data.records
  }
}
// 组件挂载完毕发送一次请求获取当前数据库当中的品牌
onMounted(() => {
  getHasTradeMark()
})
// 分页器页码发生变化的回调
const changePageNO = () => {
  getHasTradeMark()
}
// 当下拉菜单发生变化时候的回调
const sizeChange = () => {
  currentPage.value = 1
  getHasTradeMark()
}
// 添加品牌回调
const addTrade = () => {
  // 清空原本表单的数据
  tradeMarkParams.tmName = ''
  tradeMarkParams.logoUrl = ''
  tradeMarkParams.id = undefined
  dialogFormVisible.value = !dialogFormVisible.value
  // 清掉原本的错误提示
  // 第一种方式：ts
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  // 第二种方式:nextTick
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 更新品牌的回调
const updateTrade = (row: TradeMark) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  // 将表单数据展示到dialog对话框中
  tradeMarkParams.tmName = row.tmName
  tradeMarkParams.logoUrl = row.logoUrl
  // 修改数据要注意要收集id
  tradeMarkParams.id = row.id
  dialogFormVisible.value = !dialogFormVisible.value
}
// 取消对话框
const cancel = () => {
  dialogFormVisible.value = false
}
// 确认对话框
const confirm = async () => {
  // 在发送请求之前要进行整个表单的校验
  // 对整个表单进行校验之后，如果校验全部通过，再执行后续的方法
  await formRef.value.validate()
  const result: any = await reqAddOrUpdateTradeMark(tradeMarkParams)
  if (result.code == 200) {
    // 添加品牌成功
    dialogFormVisible.value = false
    ElMessage({
      type: 'success',
      message: tradeMarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 获取已有品牌的全部数据
    getHasTradeMark()
  } else {
    // 添加品牌失败
    dialogFormVisible.value = false
    ElMessage({
      type: 'error',
      message: tradeMarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}
// 上传图片之前触发的钩子函数
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 在图片上传成功之前执行，约束文件的类型和大小
  if (
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小必须小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式无比为png|jpg|gif',
    })
    return false
  }
}
// 上传图片成功的钩子函数
const successUpload: UploadProps['onSuccess'] = (response, uploadFile) => {
  // response即为当前上传图片post请求服务器返回的数据
  // 收集上传图片的地址，添加一个新的品牌的时候带给服务器
  tradeMarkParams.logoUrl = response.data
  // 图片上传成功，清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}
// 品牌自定义校验规则方法
const validatorTmName = (rule: any, value: any, callback: any) => {
  // 自定义校验规则
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称大于等于两位'))
  }
}
// 品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('LOGO图片务必上传'))
  }
}
// 表单校验规则
const rules = {
  tmName: [
    {
      required: true,
      trigger: 'change',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
}
// 气泡确认框确认按钮的回调
const deleteTradeMark = async (id: number) => {
  // 点击确认按钮删除已有品牌
  const result = await reqDeleteTradeMark(id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    // 获取已有品牌数据
    getHasTradeMark()
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>